<template>
  <div class="goods_mobile_wrap">
    <div class="goods_nav_box">
      <van-nav-bar title="货品管理" class="nav_bar_c" left-text="返回" left-arrow @click-left="onClickReturnPage">
        <template #right>
          <van-icon name="filter-o" size="22" @click="filterBtnClick" />
        </template>
      </van-nav-bar>
    </div>
    <div class="goods_list_box">
      <!-- 搜索框 -->
      <!-- <div class="search_box">
        <van-search show-action v-model="value" placeholder="请输入关键字" input-align="center">
          <template #action>
            <div @click="onClickButton" style="color: blue">搜索</div>
          </template>
        </van-search>
      </div> -->

      <!-- 操作栏 -->
      <!-- <div class="action_c_box"></div> -->

      <!-- 货品列表 -->
      <div class="good_list_col_box" id="goods_scroll_box">
        <van-empty description="暂无数据" v-if="goodsList.length == 0" />
        <van-collapse v-model="activeName" style="overflow-y: scroll" ref="collapseRef" v-else>
          <van-collapse-item
            style="box-sizing: border-box; padding: 9px 12px 5px"
            v-for="(gl, indexG) in goodsList"
            :key="indexG"
            :title="gl.name"
            :name="indexG + 1"
          >
            <div class="good_content_box">
              <!-- 实验室 -->
              <div class="good_content_item_box">
                <span class="label">实验室：</span>
                <span class="value">{{ gl.labAddress }}</span>
              </div>

              <!-- 药品柜 -->
              <div class="good_content_item_box">
                <span class="label">药品柜：</span>
                <span class="value">{{ gl.code }}</span>
              </div>

              <!-- 规格 -->
              <div class="good_content_item_box">
                <span class="label">规格：</span>
                <span class="value">{{ gl.specificDesc }}</span>
              </div>

              <!-- CAS -->
              <div class="good_content_item_box">
                <span class="label">CAS：</span>
                <span class="value">{{ gl.cas }}</span>
              </div>

              <!-- 存量 -->
              <div class="good_content_item_box">
                <span class="label">可用存量：</span>
                <span class="value">{{ gl.quantity }}</span>
              </div>

              <!-- 借出数量 -->
              <div class="good_content_item_box" v-if="gl.lendQuantity != 0">
                <span class="label">借出数量：</span>
                <span class="value">{{ gl.lendQuantity }}</span>
              </div>

              <!-- 单位 -->
              <div class="good_content_item_box">
                <span class="label">单位：</span>
                <span class="value">{{ gl.measure }}</span>
              </div>

              <!-- 类别 -->
              <div class="good_content_item_box">
                <span class="label">类别：</span>
                <span class="value">{{ gl.categoryName }}</span>
              </div>

              <!-- 制造商 -->
              <div class="good_content_item_box">
                <span class="label">制造商：</span>
                <span class="value">{{ gl.manufacturer }}</span>
              </div>

              <!-- 科目 -->
              <div class="good_content_item_box">
                <span class="label">科目：</span>
                <span class="value">{{ gl.subjectName }}</span>
              </div>

              <!-- 项目 -->
              <div class="good_content_item_box">
                <span class="label">项目：</span>
                <span class="value">{{ gl.projectName }}</span>
              </div>

              <!-- 操作按钮 -->
              <div class="operate_btn_box">
                <!-- 借还记录 -->
                <span @click="lendAndReturnLogClick(gl)">
                  <van-button class="edit_good" type="primary" size="small" icon="notes">借还记录</van-button>
                </span>
                <!-- 编辑 -->
                <span @click="editGoodsClick(gl)">
                  <van-button class="edit_good" type="primary" size="small" icon="notes">编辑货品</van-button>
                </span>
                <!-- 删除 -->
                <span @click="goodDeleteClick(gl)">
                  <van-button class="delete_good" type="danger" size="small" icon="delete">删除货品</van-button>
                </span>
              </div>
            </div>
          </van-collapse-item>
        </van-collapse>

        <div class="page_loading_box" v-if="goodsList.length != 0">
          <span>{{ goodsList.length < goodsTotal ? "正在加载更多货品" : "已经到底" }}</span>
          <van-loading class="page_loading_sp" size="12" />
        </div>
      </div>

      <!-- 底部占位盒子 -->
      <!-- <div class="footer_zw_box"></div> -->

      <!-- 
      <van-pagination
        class="pagination_c"
        v-model="queryGoodsFormData.page"
        :total-items="goodsTotal"
        :items-per-page="queryGoodsFormData.size"
      /> -->
    </div>

    <!-- 悬浮按钮 -->
    <van-floating-bubble icon="apps-o" @click="floatingBtnClick" />

    <!-- 悬浮按钮动作面板 -->
    <van-action-sheet
      v-model:show="isShowFloatingActionSheet"
      :actions="floatingBtnActions"
      @select="onActionSheetSelect"
      cancel-text="取消"
      close-on-click-action
    />

    <!-- 筛选弹出框 -->
    <van-popup v-model:show="isShowFilterPopup" position="right" :style="{ width: '84%', height: '100%' }">
      <div class="filter_popup_box">
        <div class="filter_popup_main_box">
          <!-- 货品名称 -->
          <div class="filter_form_item_box">
            <van-field v-model="queryGoodsFormData.name" label="货品名称" label-align="top" placeholder="请输入货品名称" />
          </div>

          <!-- 实验室 -->
          <div class="filter_form_item_box">
            <van-field
              v-model="queryGoodsFormData.labAddress"
              is-link
              readonly
              label="实验室"
              placeholder="请选择实验室"
              input-align="right"
              @click="isShowFilterGoodLabPicker = true"
            />
          </div>

          <!-- 类别 -->
          <div class="filter_form_item_box">
            <van-field
              v-model="queryGoodsFormData.categoryName"
              is-link
              readonly
              label="货品类别"
              placeholder="请选择货品类别"
              input-align="right"
              @click="isShowFilterGoodCategoryPicker = true"
            />
          </div>

          <!-- 药品柜 -->
          <div class="filter_form_item_box">
            <van-field v-model="queryGoodsFormData.code" label="药品柜" label-align="top" placeholder="请输入药品柜" />
          </div>

          <!-- 科目 -->
          <div class="filter_form_item_box">
            <van-field v-model="queryGoodsFormData.subjectName" label="科目" label-align="top" placeholder="请输入科目" />
          </div>

          <!-- 项目 -->
          <div class="filter_form_item_box">
            <van-field v-model="queryGoodsFormData.projectName" label="项目" label-align="top" placeholder="请输入项目" />
          </div>

          <!-- 清除选项 -->
          <div class="filter_clear_box">
            <van-button class="filter_clear_btn" color="linear-gradient(to right, #ff6034, #ee0a24)" @click="filterclearClick">
              清除选项
            </van-button>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="filter_footer_btn_box">
          <van-button class="filter_footer_btn" type="default" @click="filterPopupCancelClick">取消</van-button>
          <van-button class="filter_footer_btn" type="primary" @click="filterPopupConfirmClick">确定</van-button>
        </div>
      </div>
    </van-popup>

    <!-- 筛选货品实验室选择器 -->
    <van-popup v-model:show="isShowFilterGoodLabPicker" round position="bottom">
      <van-picker :columns="labAddressColumns" @cancel="isShowFilterGoodLabPicker = false" @confirm="labAddressPickerConfirm" />
    </van-popup>

    <!-- 筛选货品类别选择器 -->
    <van-popup v-model:show="isShowFilterGoodCategoryPicker" round position="bottom">
      <van-picker :columns="categoryColumns" @cancel="isShowFilterGoodCategoryPicker = false" @confirm="categoryPickerConfirm" />
    </van-popup>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, nextTick } from "vue";
import "./index.scss";
export default defineComponent({
  name: "GoodsMobile"
});
</script>
<script lang="ts" setup>
import {
  selectTbGoodsByPageApi,
  deleteGoodsApi,
  selectCategoryListApi,
  selectLaboratoryListApi
} from "@/api/modules/goods/index";
import { useRouter } from "vue-router";
import { showLoadingToast, closeToast, showConfirmDialog, showToast } from "vant";
import { useGoodsStore } from "@/stores/modules/goods";
import { listenScroll } from "@/utils/scroll.ts";
import JiechuIcon from "./image/jiechu.svg";
import GuihuanIcon from "./image/guihuan2.svg";
import { useLendGoodStore } from "@/stores/modules/lendGood";
import { v4 as uuidv4 } from "uuid";

const lendGoodStore = useLendGoodStore();

const goodsStore = useGoodsStore();

const router = useRouter();

const activeName = ref([]);

// 当前借还记录的货品id
// const currentLendReturnGoodId = ref(null);

// 借还记录点击事件
const lendAndReturnLogClick = good => {
  console.log(good);
  // currentLendReturnGoodId.value = good.id;
  lendGoodStore.currentLendReturnLogsGoodId = null;
  lendGoodStore.currentLendReturnLogs = [];
  router.push({
    path: "/lendReturnLogMobile/index",
    query: {
      id: good.id
    }
  });

  // lendGoodStore.lendGoodsSubListFunc();
};

// 筛选条件清除点击事件
const filterclearClick = () => {
  queryGoodsFormData.value = {
    page: 1,
    size: 30,
    labAddress: "",
    code: "",
    name: "",
    categoryName: "",
    subjectName: "",
    projectName: ""
  };
};

// 显示筛选货品实验室选择器的标识
const isShowFilterGoodLabPicker = ref(false);

// 显示筛选货品类别选择器的标识
const isShowFilterGoodCategoryPicker = ref(false);

// 实验室地址选择器确定事件
const labAddressPickerConfirm = ({ selectedOptions }) => {
  queryGoodsFormData.value.labAddress = selectedOptions[0]?.text;
  isShowFilterGoodLabPicker.value = false;
};

// 类别选择器确定事件
const categoryPickerConfirm = ({ selectedOptions }) => {
  queryGoodsFormData.value.categoryName = selectedOptions[0]?.text;
  isShowFilterGoodCategoryPicker.value = false;
};

// 筛选Popup取消点击事件
const filterPopupCancelClick = () => {
  isShowFilterPopup.value = false;
};

// 筛选Popup确定点击事件
const filterPopupConfirmClick = () => {
  queryGoodsFormData.value.page = 1;
  isShowFilterPopup.value = false;
  selectTbGoodsByPageFunc();
};

// 折叠列表Ref
const collapseRef = ref(null);

// 货品删除点击事件
const goodDeleteClick = gl => {
  showConfirmDialog({
    title: "提示",
    message: "确认要删除此货品吗?"
  })
    .then(() => {
      // on confirm
      deleteGoodsFunc(gl);
    })
    .catch(() => {
      // on cancel
    });
};

// 货品删除请求函数
const deleteGoodsFunc = async row => {
  await deleteGoodsApi(row.id)
    .then(res => {
      console.log("res", res);

      if (res.result == "success") {
        showToast("删除成功");
        console.log("删除成功");
        console.log(collapseRef.value);

        collapseRef.value?.toggleAll(false);
      } else if (res.result == "error") {
        showToast(res.msg);
      }
    })
    .catch(err => {
      showToast("删除失败");
    })
    .finally(() => {
      selectTbGoodsByPageFunc();
    });
};

// 编辑货品点击事件
const editGoodsClick = good => {
  goodsStore.mobileEditGoodsInfo = good;
  console.log(good);

  router.push({ path: "/addGoodsMobile/index" });
};

// 筛选弹出框显示的标识
const isShowFilterPopup = ref(false);

// 动作面板选择事件
const onActionSheetSelect = e => {
  console.log(e);
  switch (e.desc) {
    case "addGoods":
      router.push({
        path: "/addGoodsMobile/index"
      });
      goodsStore.mobileEditGoodsInfo = {
        id: null,
        fileId: null,
        labId: null,
        labAddress: "", //
        code: "", //
        name: "", //
        specificDesc: "", //
        cas: "",
        dangerRemark: "",
        manufacturer: "",
        measure: "",
        categoryId: null,
        categoryName: "",
        quantity: "", //
        threshold: "",
        price: "",
        subjectName: "",
        projectName: ""
      };
      break;

    case "exportTable":
      console.log("导出");
      router.push({
        path: "/exportGoodsExcelMobile/index"
      });

      break;

    case "lendGoods":
      console.log("借出");

      lendGoodStore.lendGoodsData = [
        { gid: uuidv4(), id: null, name: "", makeQuantity: 0, quantity: 0, lendQuantity: 0, lendReturnDesc: "" }
      ];
      router.push({
        path: "/lendGoodsMobile/index"
      });

      break;

    case "returnGoods":
      console.log("归还");

      lendGoodStore.lendGoodsData = [
        { gid: uuidv4(), id: null, name: "", makeQuantity: 0, quantity: 0, lendQuantity: 0, lendReturnDesc: "" }
      ];
      router.push({
        path: "/returnGoodsMobile/index"
      });

      break;

    default:
      break;
  }
};

// 悬浮按钮动作列表
const floatingBtnActions = ref([
  {
    name: "添加货品",
    icon: "add-square",
    color: "#1989fa",
    desc: "addGoods"
  },
  {
    name: "导出表格",
    icon: "printer",
    color: "#1989fa",
    desc: "exportTable"
  },
  {
    name: "借出货品",
    icon: JiechuIcon,
    color: "#1989fa",
    desc: "lendGoods"
  },
  {
    name: "归还货品",
    icon: GuihuanIcon,
    color: "#1989fa",
    desc: "returnGoods"
  }
]);

// 筛选按钮点击事件
const filterBtnClick = () => {
  isShowFilterPopup.value = !isShowFilterPopup.value;
};

// 悬浮按钮点击事件
const floatingBtnClick = () => {
  isShowFloatingActionSheet.value = !isShowFloatingActionSheet.value;
};

// 宣誓悬浮按钮动作面板的标识
const isShowFloatingActionSheet = ref(false);

// 返回点击事件
const onClickReturnPage = () => {
  router.push({
    path: "/mobileIndex/index"
  });
};

// 查询货品表单数据
const queryGoodsFormData = ref({
  page: 1,
  size: 20,
  labAddress: "",
  code: "",
  name: "",
  categoryName: "",
  subjectName: "",
  projectName: ""
});

// 货品总条数
const goodsTotal = ref(0);

// 货品列表
const goodsList = ref([]);

// 分页查询货品列表的函数
const selectTbGoodsByPageFunc = async () => {
  showLoadingToast("加载中");
  await selectTbGoodsByPageApi(queryGoodsFormData.value)
    .then(res => {
      console.log("分页查询货品列表", res);
      // 判断是第一页/中间页/最后一页
      // 当前页码
      let currentPage = queryGoodsFormData.value.page;
      // 最后一页页码
      let lastPage = Math.ceil(res.data.total / queryGoodsFormData.value.size);
      let rList = res.data.list.sort((a, b) => {
        if (a.sort === b.sort) {
          let targetA = a.name != null && a.name.toLowerCase();
          let targetB = b.name != null && b.name.toLowerCase();
          return targetA != null && targetA.localeCompare ? targetA.localeCompare(targetB) : targetA - targetB;
        }
        return a.sort - b.sort;
      });

      if (currentPage == 1) {
        console.log("第一页");
        goodsList.value = rList;
      } else if (currentPage != 1 && currentPage < lastPage) {
        console.log("不是第一页或最后一页");
        goodsList.value = goodsList.value.concat(rList);
      } else if (currentPage >= lastPage) {
        console.log("最后一页");
        goodsList.value = rList;
      }

      goodsTotal.value = res.data.total;
    })
    .finally(() => {
      closeToast();
    });
};

// 类别选择器数据
const categoryColumns = ref([]);

// 实验室地址选择器数据
const labAddressColumns = ref([]);

// 查询类别列表的函数
const selectCategoryListFunc = async () => {
  await selectCategoryListApi().then(res => {
    console.table(res.data);
    categoryColumns.value = res.data.map(item => {
      return {
        text: item.name,
        value: item.name
      };
    });
  });
};

// 查询实验室列表的函数
const selectLaboratoryListFunc = async () => {
  await selectLaboratoryListApi().then(res => {
    labAddressColumns.value = res.data.map(item => {
      return {
        text: item.address,
        value: item.id
      };
    });
  });
};

nextTick(() => {
  let scrllBoxEl = document.getElementById("goods_scroll_box");
  console.log(scrllBoxEl);

  // 触底和触顶
  listenScroll(scrllBoxEl, (isTop, isBottom) => {
    if (isTop) {
      console.log("滚动到顶部");
    }
    if (isBottom) {
      console.log("滚动到底部");
      queryGoodsFormData.value.page = queryGoodsFormData.value.page + 1;
      selectTbGoodsByPageFunc();
    }
  });
});

onMounted(() => {
  selectTbGoodsByPageFunc();
  selectCategoryListFunc();
  selectLaboratoryListFunc();
});
</script>

<style lang="scss" scoped>
:deep(.van-collapse-item) {
  border-radius: 20px;
  .van-collapse-item__title {
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
  }
  .van-collapse-item__wrapper {
    border-bottom-right-radius: 6px;
    border-bottom-left-radius: 6px;
  }
}
:deep(.filter_form_item_box) {
  .van-field--label-top {
    .van-field__label {
      padding-bottom: 8px;

      // border-width: 1px;
      border-bottom: 0.2px solid rgb(0 0 0 / 10%) !important;
    }
  }
}
</style>
